package com.egg.common.translate.util;

import com.egg.common.core.enums.ResponseCode;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.i18n.LocaleContextHolder;
import org.springframework.context.support.ReloadableResourceBundleMessageSource;

import java.util.Locale;
import java.util.Objects;

/**
 * i18n 工具类
 *
 * @author east
 */
@Slf4j
public class I18nUtil {


    private static ReloadableResourceBundleMessageSource messageSource;


    public void setMessageSource(ReloadableResourceBundleMessageSource reloadableResourceBundleMessageSource) {
        messageSource = reloadableResourceBundleMessageSource;
    }


    public static String translation(String code) {
        return translation(code, "", LocaleContextHolder.getLocale());
    }

    public static String translation(String code, String def) {
        return translation(code, def, LocaleContextHolder.getLocale());
    }

    public static String translation(String code, String def, Locale locale) {
        if (Objects.equals(code, ResponseCode.CUSTOM_ERROR.getCode().toString())) {
            return def;
        }
        try {
            return messageSource.getMessage(code, null, locale);
        } catch (Exception e) {
            log.warn("翻译:{} 编码:{} 失败, 原因: {}", locale.getLanguage(), code, e.getMessage());
            return def;
        }
    }


}